#ifndef __M_BUFFER_M__
#define __M_BUFFER_M__
#include "util.hpp"
#include "level.hpp"
#include <mutex>

namespace log
{
    #define DEFAULT_BUFFER_SIZE (1024*1024*100)
    #define THRESHOLD_BUFFER_SIZE (1024*1024*80)
    #define INCREMENT_BUFFER_SIZE (10 *1024*1024)
    class Buffer
    {
        public:
        Buffer()
        :_buffer(DEFAULT_BUFFER_SIZE,0),
        _reader_idx(0),
        _writer_idx(0)
        {
            ;
        }
        void push(const char* data,size_t len)
        {
            //1. 固定大小，则直接返回
            //if(wirteablesize() < len) return;
            //2. 动态空间，用于极限性能测试--扩容
            ensureEnoughSize(len);
            std::copy(data,data+len,&_buffer[_writer_idx]);
            moveWriter(len);
        }
        const char* begin(){return &_buffer[_reader_idx];} //返回可读数据的起始地址
        const char* get_data()
        {
            return &_buffer[_reader_idx];
        }
        size_t wirteablesize()
        {
            return _buffer.size() - _writer_idx;
        }
        size_t readablesize() //可读数据的长度 
        {
            return _writer_idx - _reader_idx;
        }                                      
        void moveReader(size_t len) //移动读指针
        {
            assert(len <= readablesize());
            _reader_idx +=len;
        }
        void reset() //重置缓冲区
        {
            _reader_idx = _writer_idx =0;
        }
        void swap(Buffer& buffer)
        {
            _buffer.swap(buffer._buffer);
            std::swap(_reader_idx,buffer._reader_idx);
            std::swap(_writer_idx,buffer._writer_idx);
        }
        bool empty()
        {
            //return readablesize() == 0?true:false;
            return _writer_idx == _reader_idx;  
        }
        private:
        //对空间进行扩容
        void ensureEnoughSize(size_t len)
        {
            if(len <= wirteablesize()) return;
            size_t newsize=0;
            if(_buffer.size() < THRESHOLD_BUFFER_SIZE)
            {
                _buffer.resize(_buffer.size() *2 +len);
            }
            else
            {
                _buffer.resize(_buffer.size() + INCREMENT_BUFFER_SIZE+len);
            }
        }
        void moveWriter(size_t len)
        {
            assert(!(len > wirteablesize()));

            _writer_idx+=len;
        }
        std::vector<char> _buffer;
        size_t _reader_idx; //当前可读数据的指针--本质是下标
        size_t _writer_idx; //当前可写数据的指针
    };
}
#endif 